const Koa = require("koa");
const app = new Koa();
const router = require("koa-router")();
const bodyParser = require('koa-bodyparser');
const { select, list } = require("./server/mysql.js");
router.post("/login", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    const res = await select(`SELECT * FROM sun WHERE name='${name}' AND pwd='${pwd}'`)
    if (res.length > 0) {
        ctx.body = {
            code: 200,
            msg: "登录成功",
            token: name + pwd
        }
    } else {
        ctx.body = {
            code: 401,
            msg: "登录失败，用户名或密码错误"
        }
    }
})

router.get("/list", async (ctx, next) => {
    const { name, pageNum, pageSize } = ctx.query;
    let data = await list(`SELECT * FROM list`)
    let search = await list(`SELECT * FROM list where name like '%${name}%' or age like '%${name}%' or sex like '%${name}%' or likes like '%${name}%' or address like '%${name}%' `)
    let dataList = await list(`SELECT * FROM list limit ${((pageNum - 1) || "0") * (pageSize || 5)},${pageSize || 5}`)
    ctx.body = {
        code: 200,
        msg: "666",
        dataList: search.length > 0 ? search : dataList,
        limit: data.length,
    }
})


app.use(bodyParser());
app.use(router.routes(), router.allowedMethods())
app.listen(3030);